package com.donfu.web.controller.house;

import java.util.Date;
import java.util.List;

import com.donfu.system.domain.house.HouseNotice;
import com.donfu.system.domain.house.HouseUser;
import com.donfu.system.domain.house.HouseUserVip;
import com.donfu.system.service.house.IHouseNoticeService;
import com.donfu.system.service.house.IHouseUserService;
import com.donfu.system.service.house.IHouseUserVipService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.donfu.common.annotation.Log;
import com.donfu.common.core.controller.BaseController;
import com.donfu.common.core.domain.AjaxResult;
import com.donfu.common.enums.BusinessType;
import com.donfu.common.utils.poi.ExcelUtil;
import com.donfu.common.core.page.TableDataInfo;

/**
 * 会员Controller
 * 
 * @author donfu
 * @date 2021-12-09
 */
@Api(tags = "后端会员管理")
@RestController
@RequestMapping("/house/vip")
public class HouseUserVipController extends BaseController
{
    @Autowired
    private IHouseUserVipService houseUserVipService;

    @Autowired
    private IHouseNoticeService houseNoticeService;

    @Autowired
    private IHouseUserService houseUserService;

    /**
     * 查询会员列表
     */
    @ApiOperation("查询会员列表")
    @PreAuthorize("@ss.hasPermi('house:vip:list')")
    @GetMapping("/list")
    public TableDataInfo list(HouseUserVip houseUserVip)
    {
        startPage();
        List<HouseUserVip> list = houseUserVipService.selectHouseUserVipList(houseUserVip);
        return getDataTable(list);
    }

    ///**
    // * 导出会员列表
    // */
    //@PreAuthorize("@ss.hasPermi('house:vip:export')")
    //@Log(title = "会员", businessType = BusinessType.EXPORT)
    //@GetMapping("/export")
    //public AjaxResult export(HouseUserVip houseUserVip)
    //{
    //    List<HouseUserVip> list = houseUserVipService.selectHouseUserVipList(houseUserVip);
    //    ExcelUtil<HouseUserVip> util = new ExcelUtil<HouseUserVip>(HouseUserVip.class);
    //    return util.exportExcel(list, "会员数据");
    //}

    /**
     * 获取会员详细信息
     */
    @ApiOperation("获取会员详情")
    @PreAuthorize("@ss.hasPermi('house:vip:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return AjaxResult.success(houseUserVipService.selectHouseUserVipById(id));
    }

    /**
     * 新增会员
     */
    @ApiOperation("新增会员")
    @PreAuthorize("@ss.hasPermi('house:vip:add')")
    @Log(title = "会员", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody HouseUserVip houseUserVip)
    {
        // 检测参数是否合格
        AjaxResult ajaxResult = checkHouseUserVip(houseUserVip);
        String code = ajaxResult.get("code").toString();
        if(code.contains("50")){
            return  ajaxResult;
        }
        // 检查是否存在此用户的数据
        HouseUserVip vip=new HouseUserVip();
        vip.setUserId(houseUserVip.getUserId());
        List<HouseUserVip> list = houseUserVipService.selectHouseUserVipList(vip);
        if(list!=null && list.size()>0){
            return AjaxResult.error("此用户数据在列表中已存在");
        }
        return toAjax(houseUserVipService.insertHouseUserVip(houseUserVip));
    }

    /**
     * 会员审批
     */
    @ApiOperation("会员审批")
    @PostMapping("/audit")
    public AjaxResult audit(@RequestBody HouseUserVip userVip){
        int i = houseUserVipService.updateHouseUserVip(userVip);
        // 如果修改成功,则对下面的审核状态进行判断操作
        if(i>0){
            Integer isAllow = userVip.getIsAllow();
            Long userId=userVip.getUserId();
            if(isAllow==1){
                // 修改house_user表中此用户的会员状态
                HouseUser houseUser=new HouseUser();
                houseUser.setId(userId);
                // 修改用户状态为超级会员
                houseUser.setRole(1);
                houseUserService.updateHouseUser(houseUser);
                // 如果审核通过，发送消息给客户
                HouseNotice houseNotice=new HouseNotice();
                // 标题
                houseNotice.setTitle("成为会员通知");
                // 发送给谁
                houseNotice.setUserId(userId);
                // 创建时间
                houseNotice.setCreateDate(new Date());
                // 用户是否已读 1 已读 0 未读
                houseNotice.setState(0);
                // 通知内容
                houseNotice.setContent("尊敬的"+userVip.getRealName()+"用户,恭喜您成为会员，感谢您的支持与信赖！");
                houseNoticeService.insertHouseNotice(houseNotice);

            }else if(isAllow==2){
                // 如果审核通过，发送消息给客户
                HouseNotice houseNotice=new HouseNotice();
                // 标题
                houseNotice.setTitle("成为会员失败通知");
                // 发送给谁
                houseNotice.setUserId(userId);
                // 创建时间
                houseNotice.setCreateDate(new Date());
                // 用户是否已读 1 已读 0 未读
                houseNotice.setState(0);
                // 通知内容
                houseNotice.setContent("尊敬的"+userVip.getRealName()+"用户,抱歉您并未成为会员，感谢您的支持与信赖！");
                houseNoticeService.insertHouseNotice(houseNotice);
            }
        }
        return toAjax(i);
    }

    /**
     * 修改会员
     */
    @ApiOperation("修改会员")
    @PreAuthorize("@ss.hasPermi('house:vip:edit')")
    @Log(title = "会员", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody HouseUserVip houseUserVip)
    {
        if(houseUserVip.getId()==null){
            return AjaxResult.error("id不能为空");
        }
        AjaxResult ajaxResult = checkHouseUserVip(houseUserVip);
        String code = ajaxResult.get("code").toString();
        if(code.contains("50")){
            return  ajaxResult;
        }
        return toAjax(houseUserVipService.updateHouseUserVip(houseUserVip));
    }


    /**
     * 删除会员
     */
    @ApiOperation("删除会员")
    @PreAuthorize("@ss.hasPermi('house:vip:remove')")
    @Log(title = "会员", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        return toAjax(houseUserVipService.deleteHouseUserVipByIds(ids));
    }

    public AjaxResult checkHouseUserVip(HouseUserVip userVip){
        String realName = userVip.getRealName();
        if(realName==null || realName.equals("")){
            return AjaxResult.error("会员姓名不能为空");
        }
        if(realName.length()>100){
            return AjaxResult.error("会员姓名长度过长");
        }
        Integer sex = userVip.getSex();
        if(sex==null){
            return AjaxResult.error("性别不能为空");
        }
        if (sex!=1 && sex!=2){
            return AjaxResult.error("请正常的选择性别");
        }
        String userPhone = userVip.getUserPhone();
        if(userPhone==null){
            return AjaxResult.error("手机号码不能为空");
        }
        String regexPhone = "^(1[0-9])\\d{9}$";
        boolean matches = userPhone.matches(regexPhone);
        if (!matches) {
            return AjaxResult.error("手机号码格式不正确");
        }
        Long userId = userVip.getUserId();
        if(userId==null){
            return AjaxResult.error("用户id不能为空");
        }
        return AjaxResult.success();
    }

}
